package controller.UserController;

import com.fasterxml.jackson.databind.ObjectMapper;
import common.ResultAjax;
import services.UserService;
import services.impl.UserServiceImpl;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @auther hewenhui
 * @see <a href="hetp://www.codingmaster.com> java </a>
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet{
    ObjectMapper objectMapper = new ObjectMapper();
    //控制层调用服务层
    UserService userService = new UserServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/json; charset=utf-8");
        // 1、校验
        // 校验登陆身份
        HttpSession session = req.getSession(false);
        if (session != null) {
            // 当前就是未登录状态, 谈不上退出登录!
            // resp.sendRedirect("login.html");
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"已经登录，请注销后注册！"));
            resp.getWriter().write(respJson);
            return ;
        }
        // 校验参数
        String phone_number = req.getParameter("phone_number");
        String password = req.getParameter("password");
        String confirm_password = req.getParameter("confirm_password");
        if(StringUtil.isEmpty(phone_number)
                ||StringUtil.isEmpty(password)
                ||StringUtil.isEmpty(confirm_password)
                ||!password.equals(confirm_password)){
            String respJson = objectMapper.writeValueAsString(ResultAjax.fail(-1,"参数有误！"));
            resp.getWriter().write(respJson);
        }

        // 2、添加用户
        int i = userService.addUser(phone_number, password);
        // 注册成功
        if(i==1){
            String respJson = objectMapper.writeValueAsString(ResultAjax.succeed(200,"注册成功，点击确定，跳转至登录页面",null));
            resp.getWriter().write(respJson);
        }else{

        }
    }
}



